<?php

class ArticlesController extends AppController
{

    var $uses = array('Article', 'Congress', 'Area');
    var $layout = 'author_default';

    function author_view($articleId)
    {
        $this->set('article', $this->Article->read(null, $articleId));
        $this->set('userId', $this->Session->read('Auth.User.id'));
    }

    function author_submit($congressId)
    {
        $congress = $this->Article->Congress->read(null, $congressId);

        if (date('Y-m-d', strtotime($congress['Congress']['deadline_submission'])) <= date('Y-m-d')) {
            $this->Session->setFlash(__('Período para submeter artigos está encerrado.', true));
            $this->redirect(array('author' => true, 'controller' => 'users', 'action' => 'profile'));
        } else {
            if (!empty($this->data)) {
                $user_id = $this->data['Article']['user_id'] = $this->Session->read('Auth.User.id');
                $area_id = $this->data['Article']['area_id'];
                $newFileName = $user_id . '-' . $congressId . '-' . $area_id . '.pdf';

                if (!$this->Upload->copyUploadedFile($this->data['Article']['file'], 'files', $newFileName)) {
                    $this->Session->setFlash($this->Upload->getLog());
                } else {
                    $this->data['Article']['file_path'] = '/files/' . $newFileName;

                    $this->Article->create();
                    if ($this->Article->save($this->data)) {
                        $this->Session->setFlash(__('Artigo submetido com sucesso.', true));
                        $this->redirect(array('controller' => 'congresses', 'action' => 'view', $congressId));
                    } else {
                        $this->Session->setFlash(__('Erro ao adicionar o artigo.', true));
                    }
                }
            }
        }
        $this->set('congress', $congress);

        $a = array();

        $areas = $this->Area->findAreas($congressId);

        foreach ($areas as $area) {
            $a[$area['areas']['id']] = $area['areas']['name'];
        }
        $this->set('areas', $a);
    }

    function author_edit($articleId)
    {
        $article = $this->Article->read('congress_id', $articleId);
        $congress = $this->Congress->read('deadline_submission', $article['Article']['congress_id']);

        if (strtotime($congress['Congress']['deadline_submission']) <= time()):
            $this->Session->setFlash(__('Período para submeter artigos está encerrado. Você não pode editar este artigo.', true));
            $this->redirect(array('author' => true, 'controller' => 'congresses', 'action' => 'view', $congress['Congress']['id']));
        else:
            if (empty($this->data)):
                $this->data = $this->Article->read(null, $articleId);
            else:
                if ($this->Article->save($this->data)):
                    $this->Session->setFlash(__('O Artigo foi salvo.', true));
                    $this->redirect(array('controller' => 'articles', 'action' => 'view', $articleId));
                else:
                    $this->Session->setFlash(__('Erro ao salvar o Artigo.', true));
                endif;
            endif;
        endif;

        $areas = $this->Area->findAreas($article['Article']['congress_id']);

        $a = array();
        
        foreach ($areas as $area) {
            $a[$area['areas']['id']] = $area['areas']['name'];
        }
        $this->set('areas', $a);

        $this->set('article', $this->data = $this->Article->read(null, $articleId));
    }

    function author_delete($articleId)
    {
        $article = $this->Article->read(null, $articleId);
        $congress = $this->Congress->read('deadline_submission', $article['Article']['congress_id']);

        if (strtotime($congress['Congress']['deadline_submission']) <= time()):
            $this->Session->setFlash(__('Período para submeter artigos está encerrado. Você não pode excluir este artigo.', true));
            $this->redirect(array('author' => true, 'controller' => 'congresses', 'action' => 'view', $congress['Congress']['id']));
        else:
            if ($this->Article->delete($articleId) && unlink(APP . WEBROOT_DIR . eregi_replace("/", DS, $article['Article']['file_path']))) {
                $this->Session->setFlash(__('O Artigo foi excluído', true));
                $this->redirect('/author/congresses/view/' . $article['Article']['congress_id']);
            }
        endif;
    }

    function finalList($congressId)
    {
        $this->layout = 'public_default';

        $congress = $this->Article->Congress->read(null, $congressId);
        $this->set('congress', $congress);

        if ($congress['Congress']['status'] == 'E'):
            $articles = $this->Article->find('all', array('conditions' => array('congress_id' => $congressId), 'order' => 'Article.final_grade DESC'));
            $this->set('articles', $articles);
        else:
            $this->set('status', $congress['Congress']['status']);
        endif;
    }

    function evaluationDetails($congressId, $articleId)
    {
        $this->layout = 'public_default';

        $congress = $this->Article->Congress->read(null, $congressId);
        $this->set('congress', $congress);

        if ($congress['Congress']['status'] == 'E'):
            $article = $this->Article->read(null, $articleId);
            $this->set('article', $article);
        else:
            $this->set('status', $congress['Congress']['status']);
        endif;
    }

// Finaliza a avaliação de todos os artigos do congresso
    function coordinator_finalizeArticleEvaluation($congressId)
    {
        $congress = $this->Congress->read(null, $congressId);
        if ((date('Y-m-d', strtotime($congress['Congress']['deadline_evaluation'])) < date('Y-m-d')) && ($congress['Congress']['status'] == 'S')):
            $a = $this->Article->query("
                SELECT
                    `article_id`,
                    AVG(`mean_grade`) AS `final_grade`,
                    AVG(`originality_grade`) AS `final_originality_grade`,
                    AVG(`relevance_grade`) AS `final_relevance_grade`,
                    AVG(`text_grade`) AS `final_text_grade`,
                    AVG(`general_grade`) AS `final_general_grade`
                FROM `evaluations` AS `Evaluation`
                GROUP BY `article_id`
                ");

            foreach ($a as $k => $article) {
                $this->data['Article']['id'] = $a[$k]['Evaluation']['article_id'];
                $this->data['Article']['final_grade'] = $a[$k][0]['final_grade'];
                $this->data['Article']['final_originality_grade'] = $a[$k][0]['final_originality_grade'];
                $this->data['Article']['final_relevance_grade'] = $a[$k][0]['final_relevance_grade'];
                $this->data['Article']['final_text_grade'] = $a[$k][0]['final_text_grade'];
                $this->data['Article']['final_general_grade'] = $a[$k][0]['final_general_grade'];

                $this->Article->save($this->data);
            }

            $this->Session->setFlash(__('O período de Avaliação foi Encerrado.', true));
            $this->Article->query("UPDATE `congresses` SET `congresses`.`status` = 'E' WHERE `congresses`.`id` = '$congressId'");
            $this->redirect(array('controller' => 'congresses', 'action' => 'index'));
        endif;
    }

}

?>
